// pages/confirm_order/index.js
import {
    ReDistributionMall,
    ReMallPay
} from "../../api/shipping.js"
import {
    getNavigationbar
} from "../../api/index.js"
import {
    Decimal
} from '../../utils/decimal.js'
import {

    ReMallShopping
} from "../../api/index.js"
Page({
    options: {

        styleIsolation: 'shared'
    },
    /**
     * 页面的初始数据
     */


    data: {
        showModal: false,
        totalNumbers: 0,
        isSlot: false,
        addressresList: [],
        modalTitle: "",
        message: "",
        type: '',
        confirmText: "",
        cancelText: "",
        toleNum:0,
      
        showCancelButton: false,
        scrollViewHeight: 0,
        orderList: [],
        isCoupon: false,
        note: '',
        out_trade_no: ''
    },

    /**
     * 选择优惠券回调函数方法
     */
    handleSelCoupon() {
        this.setData({
            isCoupon: true
        })
    },
    /**
     * 跳转
     * @param {*} event 
     */
    enter(event) {
        console.log('e', event)
        let obj = {
            ...event.currentTarget.dataset.value,
            agent_name: event.currentTarget.dataset.value.name,
            agent_thumb: event.currentTarget.dataset.value.logo
        }
        let objStr = encodeURIComponent(JSON.stringify(obj));
        wx.navigateTo({
            url: '/pages/brand_detail/index?obj=' + objStr,
        })
    },
    // 检测订单支付状态的函数
    checkPaymentStatus() {
        if (this.data.out_trade_no != '') {
            ReMallShopping({
                act: 'check_order_state',
                out_trade_no: this.data.out_trade_no,

            }).then(res => {
                if (res.ispay == 1) {
                    wx.reLaunch({
                        url: '/pages/order_list/index',
                    })
                } else {
                    wx.showModal({
                        title: '',
                        content: '订单未支付',
                        showCancel: false, // 是否显示取消按钮，设为false表示不显示
                        confirmText: '确定', // 确定按钮的文本
                        success(res) {
                            if (res.confirm) {
                                console.log('用户点击确定');
                                wx.redirectTo({
                                    url: '/pages/order_list/index',
                                })
                            }
                        }
                    });
                }
                console.log('检测订单支付状态的函数', res)
            })
        }
    },
    /**
     * 进货商城收获地址列表
     */
    getAddressres(item) {
        getNavigationbar({
            act: 'addressres',
            p: '1',
            rol1page: 10000,
            type: 'getlist' //getlist-获取地址列表 editor-编辑 add-新增 singleaddr-根据id获取地址
        }).then(res => {
            console.log('是是是', res)
            res.forEach(element => {
                if (element.id == this.data.params.address_id) {
                    console.log('res===>', element)
                    let datalist = []
                    datalist.push(element)
                    this.setData({
                        addressresList: datalist
                    })
                }
            });

            console.log('进货商城收获地址列表', res)
        })
    },
    /**
     * 支付
     */
    payment() {
        console.log('支付')
        ReDistributionMall({
            act: 'oneCommitorder',
            paytype: 2,
            remove_postage: '1',
            addressid: this.data.params.address_id,
            note: this.data.note,
            sealmanid: '',
            remove_postage: '1'
        }).then(resj => {
            console.log('支付', resj)
            if (resj.result == 101) {
                return wx.showModal({
                    title: '',
                    content: resj.msg,
                    showCancel: false, // 是否显示取消按钮，设为false表示不显示
                    confirmText: '确定', // 确定按钮的文本
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定');
                        }
                    }
                });
            }
            this.data.out_trade_no = resj.out_trade_no
            let openids = wx.getStorageSync('OPENID')

            let token = wx.getStorageSync('TOKEN')
            ReMallPay({
                act: "mini_wechat_commit",
                appid: 'wx11508f3ee9dd6329',
                openid: openids,
                channel: "",
                "out_trade_no": resj.out_trade_no
            }).then(res => {
                let that = this;
                console.log('微信支付', res, 'token', res.path + '?out_trade_no=' + resj.out_trade_no + '&token=' + token)
                if (res.channel == 'mini_wechat') {
                    // 跳转到汇付小程序进行支付操作
                    wx.navigateToMiniProgram({
                        appId: res.appid,

                        envVersion: 'trial',
                        path: res.path + '?out_trade_no=' + resj.out_trade_no + '&token=' + token + '&type=mini_program',
                        success(res) {
                            setTimeout(() => {
                                that.checkPaymentStatus()
                            }, 1000);
                            // 支付完成后返回的回调函数

                        },
                        fail(res) {
                            console.log('res123', )
                            setTimeout(() => {
                                that.checkPaymentStatus()
                            }, 1000);
                            // 跳转失败的处理逻辑

                        }
                    });
                } else {
                    wx.requestPayment({
                        provider: "wxpay",
                        appid: "wx11508f3ee9dd6329",
                        timeStamp: res.timestamp,
                        nonceStr: res.noncestr,
                        package: res.package,
                        partnerid: res.partnerid,
                        signType: res.sign_type,
                        paySign: res.sign,
                        success: function (res) {
                            // 支付成功的回调
                            console.log('支付成功的回调', res)
                            wx.navigateTo({
                                url: '/pages/order_list/index',
                            })
                        },
                        fail: function (res) {
                            // 支付失败的回调
                            console.log('支付失败的回调', res)

                            wx.showModal({
                                title: '111',
                                content: res.msg,
                                showCancel: false, // 是否显示取消按钮，设为false表示不显示
                                confirmText: '确定', // 确定按钮的文本
                                success(res) {
                                    if (res.confirm) {
                                        wx.navigateTo({
                                            url: '/pages/order_list/index',
                                        })
                                    }
                                }
                            });
                        }
                    });

                }


            })

        });
    },
    yuanToFen(yuan) {
        return Math.round(yuan * 100); // 将元转换为分，取整
    },
    handleGoodsDetail(e) {
        console.log('e', e)
        this.data.note = e.detail.value
    },
    /**
     * 一件代发-订单确认
     */
    getOneComfirmCart(item) {
        ReDistributionMall({
            act: 'oneComfirmCart',
            addressid: this.data.params.address_id,
            coupons: '',
            remove_postage: '1'
        }).then(res => {
            console.log('res1', res)
            if (res.result == 101 && res.msg == '请选择收获地址') {
                wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            wx.reLaunch({
                                url: '/pages/address_management/index',
                            })

                        }
                    }
                })
            } else if (res.result == 101) {
                wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false,
                    success(res) {
                        if (res.confirm) {
                            console.log('用户点击确定')
                            wx.navigateBack()
                        }
                    }
                })
            } else {
                let toleNum = ''
                res.forEach(element => {
                    let num = element.total + element.logistics.postage
                    if (this.data.params.type != 10) {
                        Object.assign(element, {
                            num:parseFloat(num).toFixed(2) // 一件代发
                        })
                    } else {
                        Object.assign(element, {
                            num: parseFloat(num).toFixed(2) // 一件代发
                        })
                    }
                    element.brand.forEach(elementj => {
                       this.data.totalNumbers =  elementj.numbers
                    });
                    toleNum = +element.num
                });
                console.log('获取', toleNum)
                this.setData({
                    orderList: res,
                    totalNumbers: this.data.totalNumbers
                })
            }
            const total = res.reduce((acc, cur) => this.calcFn(acc, cur.num), 0)
            console.log('一件代发-订单确认', res, total)

            this.setData({

                toleNum: parseFloat(total).toFixed(2)
            })
        });
    },
    calcFn(num1 = 0, num2 = 0) {
        const n1 = new Decimal(num1)
        const n2 = new Decimal(num2)
        const sum = n1.plus(n2)
        return sum.toString()
    },
    /**
     * 关闭弹窗回调函数方法
     */
    handleClose() {
        this.setData({
            isCoupon: false
        })
    },
    /**
     * 提示弹窗确认回调函数方法
     */
    handleModalChange(e) {
        const type = e.detail
        if (type == "confirm") {
            this.setData({
                showModal: false
            })
        } else {
            this.setData({
                showModal: false
            })
            // getApp().Tips({ title: "操作已取消" })
        }
    },
    /**
     * 计算页面可滚动区域的动态高度
     */
    computeScrollViewHeight() {
        let that = this
        wx.getSystemInfo({
            success: function (res) {
                const windowHeight = res.windowHeight;
                console.log('手机屏幕高度：', windowHeight);

                // 进行适配操作，例如设置元素高度为屏幕高度的一半
                const halfScreenHeight = windowHeight / 2;
                console.log('屏幕高度的一半：', halfScreenHeight);
                that.setData({
                    scrollViewHeight: windowHeight - 190
                })
            }
        });
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.data) {
            let params = JSON.parse(options.data)
            this.data.params = {
                ...params
            }
            // this.data.params.address_id = params.addressId
            console.log('进', params, this.data.params)
            this.setData({
                // totalNumbers: params.totalNumbers,
                type: params.type
            })

        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        wx.nextTick(() => {
            this.getOneComfirmCart(this.data.params);
            this.getAddressres();
        })
        this.computeScrollViewHeight();
        // this.checkPaymentStatus();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})